package handler

import (
	"fmt"
	"choujiang/box_server/service"
	"choujiang/common/models"
	"choujiang/common/utils"
	"strconv"

	"github.com/gin-gonic/gin"
	"choujiang/common/consts"
)

func Log(c *gin.Context) {
	var log model.Log
	if err := c.ShouldBind(&log); err == nil {
		fmt.Printf("model.Log:%+v\n", log)
		go service.SaveLog(log)
	} else {
		fmt.Printf("model.Log err:%+v\n", err)
	}
	utils.JSON("ok", c)
}

/**
 @description 通过sdk判断用户是否游玩成功
 @return
 @author guxiang
 @version v1 2018-11-24
 */
func SdkLog(c *gin.Context) {
	uniqueId := c.Request.Form.Get("uniqueId")
	token := c.Request.Form.Get("shareToken")
	gameId := c.Request.Form.Get("gameId")
	openId := c.Request.Form.Get("openId")
	appId := c.Request.Form.Get("appId")
	if service.CheckLock(gameId, uniqueId) { //判断是否有锁
		utils.JSON("fail", c)
		return
	}
	go func() {
		user := model.GetUserByUniqueId(uniqueId)
		if user == nil {
			utils.Error(consts.ErrUserNotFound, c)
			return
		}
		errType := service.PlaySdkGame(user, appId, openId, gameId, token)
		if errType != nil {
			utils.Error(errType, c)
			return
		}
	}()

	utils.JSON("ok", c)
}

/**
 @description 判断请求是否有效
 */
func CheckLog(c *gin.Context) {
	token := c.Request.Form.Get("shareToken")
	scene := c.Request.Form.Get("scene")
	goodsId := c.Request.Form.Get("goodsId")
	var log model.Log
	if service.CheckLock(log.ToGame, log.UniqueId) { //判断是否有锁
		fmt.Printf("CheckLock err: %s\n", "request was locked")
		utils.JSON("fail", c)
		return
	}
	if err := c.ShouldBind(&log); err == nil {
		//判断是否领取奖励
		goodsId64, _ := strconv.ParseInt(goodsId, 10, 64)
		err := service.ReceiveRewardFromJumpLog(log, token, scene, goodsId64)
		if err != nil {
			fmt.Printf("ReceiveRewardFromJumpLog err: %s", err)
			utils.JSON("fail", c)
			return
		}
	} else {
		fmt.Printf("CheckLog err: %s", "bind log model failed")
		utils.JSON("fail", c)
		return
	}

	utils.JSON("ok", c)
}
